import * as THREE from "three";

import Stats from "three/addons/libs/stats.module.js";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";

window.onload = () => {
  const container = document.getElementById("container");

  let renderer, scene, camera, stats;
  let mesh;

  let line;

  const texture = new THREE.TextureLoader().load("./cover.png");
  const texture2 = new THREE.TextureLoader().load("./black.jpg");
  texture2.repeat.set(1, 1); // 可选：设置纹理的重复次数
  texture2.wrapS = texture2.wrapT = THREE.RepeatWrapping; // 可选：设置纹理的环绕方式
  texture2.needsUpdate = true; // 更新纹理

  // 设置纹理的编码方式为线性编码
  texture.encoding = THREE.sRGBEncoding;

  // 设置纹理旋转中心
  texture.center.set(0.5, 0.5); // 将纹理的中心点设置为(0.5, 0.5)
  window.scaleTexture = scaleTexture;
  window.rotateTexture = rotateTexture;

  texture.needsUpdate = true;

  function scaleTexture(x, y) {
    // 缩放纹理
    texture.wrapS = THREE.ClampToEdgeWrapping;
    texture.wrapT = THREE.ClampToEdgeWrapping;
    texture.repeat.set(1 / x, 1 / y); // 在U和V方向上重复两次
  }

  var uvMaterial = new THREE.MeshStandardMaterial({ map: texture });

  texture.wrapS = THREE.ClampToEdgeWrapping;
  texture.wrapT = THREE.ClampToEdgeWrapping;
  //调整纹理过滤：在某些情况下，拖影可能是由于纹理过滤设置不当造成的。你可以尝试调整纹理的过滤方式，例如使用texture.minFilter = THREE.NearestFilter来避免纹理采样插值。
  //texture.minFilter = THREE.NearestFilter;
  texture.magFilter = THREE.LinearFilter;
  texture.minFilter = THREE.LinearFilter;

  function rotateTexture(angle) {
    // 设置纹理旋转
    texture.rotation = -angle * (Math.PI / 180); // 旋转45度
  }

  var cameraOriginalPosition = new THREE.Vector3();
  var cameraOriginalRotation = new THREE.Euler();
  init();
  animate();

  function init() {
    renderer = new THREE.WebGLRenderer({ antialias: true });

    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(280, 280);
    // renderer.setSize(window.innerWidth, window.innerHeight);
    container.appendChild(renderer.domElement);

    stats = new Stats();
    container.appendChild(stats.dom);

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(45, 1, 1, 1000);
    camera.position.z = 120;

    // 保存原始位置和旋转角度
    cameraOriginalPosition.copy(camera.position);
    cameraOriginalRotation.copy(camera.rotation);

    const controls = new OrbitControls(camera, renderer.domElement);
    controls.minDistance = 50;
    controls.maxDistance = 200;

    // scene.add(new THREE.AmbientLight(0x443333));

    const dirLight1 = new THREE.DirectionalLight(0xffffff, 1);
    dirLight1.position.set(1, 0.75, 0.5);
    scene.add(dirLight1);

    const dirLight2 = new THREE.DirectionalLight(0xccccff, 1);
    dirLight2.position.set(-1, 0.75, -0.5);
    scene.add(dirLight2);
    // // 光源设置（可选）
    // var ambientLight = new THREE.AmbientLight(0xccccff);
    // scene.add(ambientLight);

    const geometry = new THREE.BufferGeometry();
    geometry.setFromPoints([new THREE.Vector3(), new THREE.Vector3()]);

    line = new THREE.Line(
      geometry,
      new THREE.LineBasicMaterial({ color: 0xff0000 })
    );
    scene.add(line);

    loadGLB();

    window.addEventListener("resize", onWindowResize);
  }
  let originalRotation = null;

  function loadGLB() {
    const dracoLoader = new DRACOLoader();
    dracoLoader.setDecoderPath("jsm/libs/draco/gltf/");

    const loader = new GLTFLoader();
    loader.setDRACOLoader(dracoLoader);
    //http://nimg5.hicustom.com/static/threeDimensionFile/C7NNUWKGW7FZB-3dSources.glb
    loader.load("./B7EP6AI4TDU3L-3dSources.glb", function (gltf) {
      mesh = gltf.scene.children[0];

      // mesh.traverse(function(child) {
      //   if (child instanceof THREE.Mesh) {
      //     child.material = uvMaterial;
      //   }
      // });

      // var normalMaterial = new THREE.MeshNormalMaterial();
      // // 遍历模型的每个子网格
      // mesh.traverse(function (child) {
      //   if (child.isMesh) {
      //     // 设置法线可视化材质
      //     child.material = normalMaterial;
      //   }
      // });

      originalRotation = mesh.rotation.clone();
      mesh.scale.set(30, 30, 30);
      rotateMesh(1);

      scene.add(mesh);
    });
  }
  let initFlag = true;
  var initialUVsX = [];
  var initialUVsY = [];
  let currentWidget = 5;
  function updateUv(x, y, scaleX, scaleY) {
    var geometry = mesh.children[currentWidget].geometry;
    var uvAttribute = geometry.getAttribute("uv");

    if (initFlag) {
      let xarr = [];
      let yarr = [];
      for (var i = 0; i < uvAttribute.count; i++) {
        xarr.push(uvAttribute.getX(i));
        yarr.push(uvAttribute.getY(i));
      }
      initialUVsX = xarr;
      initialUVsY = yarr;
      initFlag = false;
    }

    for (var i = 0; i < uvAttribute.count; i++) {
      // 限制UV坐标在[0, 1]范围内
      let u = Math.max(
        -0.1,
        Math.min(initialUVsX[i] / scaleX + x / scaleX, 1.1)
      );
      let v = Math.max(
        -0.1,
        Math.min(initialUVsY[i] / scaleY - y / scaleY, 1.1)
      );

      // 更新UV坐标
      uvAttribute.setXY(i, u, v);
      // uvAttribute.setXY(
      //   i,
      //   initialUVsX[i] / scaleX + x / scaleX,
      //   initialUVsY[i] / scaleY - y / scaleY
      // );
    }

    uvAttribute.needsUpdate = true;
  }

  window.updateUv = updateUv;
  window.rotateMesh = rotateMesh;
  function rotateMesh(v) {
    initFlag = true;
    // updateUv();
    // 保存模型的原始旋转效果
    mesh.rotation.copy(originalRotation);
    let vrotate = 1;

    switch (v) {
      case 1:
        vrotate = 1;
        currentWidget = 5;
        mesh.children[5].material = new THREE.MeshPhongMaterial();

        mesh.children[5].material.map = texture;
        mesh.children[5].material.alphaMap = texture2;
        mesh.children[5].needsUpdate = true;
        // console.log(1231231,mesh.children[5].material)
        // mesh.children[5].material.envMap = texture2;
        //  mesh.children[5].material.map = texture2;
        //  mesh.children[5].material.map2 = texture;
        break;
      case 2:
        vrotate = 2;
        currentWidget = 4;
        mesh.children[4].material = uvMaterial;
        mesh.children[4].needsUpdate = true;
        break;
      case 3:
        vrotate = 1.5;
        currentWidget = 2;
        mesh.children[2].material = uvMaterial;
        break;
      case 4:
        vrotate = 0.5;
        currentWidget = 3;
        mesh.children[3].material = uvMaterial;
        break;
      case 5:
        vrotate = 2;
        currentWidget = 0;
        mesh.children[0].material = uvMaterial;
        break;
    }

    // 重置相机位置和旋转角度
    camera.position.copy(cameraOriginalPosition);
    camera.rotation.copy(cameraOriginalRotation);

    mesh.rotateOnAxis(new THREE.Vector3(0, 1, 0), vrotate * Math.PI); // 围绕Y轴旋转180度

    //mesh.updateMatrix();
  }

  function onWindowResize() {
    // camera.aspect = window.innerWidth / window.innerHeight;
    camera.aspect = 280 / 280;
    camera.updateProjectionMatrix();

    renderer.setSize(280, 280);
  }

  function animate() {
    requestAnimationFrame(animate);

    renderer.render(scene, camera);

    stats.update();
  }
};
